package com.tust.app.controller;

import com.tust.app.domain.User;
import com.tust.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
//@RequestMapping("/api")
public class AdminController {
    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public String ad(){
        return "redirect:/login.jsp";
    }

    @RequestMapping("/adminLogin")
    public String adLogin(String username, String password){
        return "redirect:admin/home.jsp";
    }

    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, HttpSession session) {
        User user = userService.findByUsernameAndPassword(username, password);
        if (user != null) {
            session.setAttribute("currentUser", user); // 将用户对象存储到Session中
            int roleId = user.getRoleId();
            if (roleId == 1) {
                return "redirect:/home.jsp";
            } else if (roleId == 2) {
                return "redirect:admin/home.jsp";
            } else {
                return "Unauthorized role";
            }
        } else {
            return "Invalid username or password";
        }
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestParam String username, @RequestParam String password, @RequestParam String email) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setState(1);
        user.setRoleId(1); // 默认状态

        try {
            userService.insert(user);
            // 注册成功后重定向到用户列表页面
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            // 注册失败后返回错误页面或提示
            return "error.jsp";
        }
    }

    @PostMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate(); // 清除Session中的所有信息
        return "redirect:/login.jsp";
    }

}